﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FlashPay.DAO.Impl
{
    using FlashPay.DAO.Interface;
    using FlashPay.EF;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Response.SysAnnouncement;
    using Microsoft.EntityFrameworkCore;
    using System.Linq;

    /// <summary>
    /// 公告数据接口现实
    /// </summary>
    public class SysAnnouncementDaoImpl : SysAnnouncementDao
    {
        #region 注入
        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="context"></param>
        public SysAnnouncementDaoImpl(FlashPayContext context)
        {
            _context = (FlashPayContext)context;
        }

        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <returns></returns>
        public JResult<SysAnnouncementResponse> Get(int id)
        {
            var result = new JResult<SysAnnouncementResponse>() {
                Success = true
            };

            var model = _context.SysAnnouncement.Where(p => p.AnnouncementId.Equals(id)).FirstOrDefault();
            if (model != null)
            {
                var nowTime = DateTime.Now;

                var sysAnnouncementResponse = new SysAnnouncementResponse()
                {
                    AnnouncementId = model.AnnouncementId,
                    Popups = model.Popups,
                    Subject = model.Subject,
                    Content = model.Content,
                    Sdate = model.Sdate.ToString("yyyy-MM-dd HH:mm:ss"),
                    Edate = model.Edate.ToString("yyyy-MM-dd HH:mm:ss"),
                    Valid = (model.Sdate <= nowTime && model.Edate >= nowTime) ? (sbyte)1 : (sbyte)0,
                    CreateId = model.CreateId,
                    CreateDate = model.CreateDate
                };

                result.Data = sysAnnouncementResponse;
            }
            else
            {
                result.Success = false;
                result.ErrorMessage = "记录不存在";
            }

            return result;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(SysAnnouncement model)
        {
            _context.SysAnnouncement.Add(model);
            //调用数据上下文的保存方法，将对象存数数据库
            var resultId = _context.SaveChanges();

            return resultId;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        public bool Update(SysAnnouncement model)
        {
            bool result = false;

            var sysAnnouncement = _context.SysAnnouncement.Where(p=>p.AnnouncementId.Equals(model.AnnouncementId)).FirstOrDefault();
            if (sysAnnouncement != null)
            {
                sysAnnouncement.AnnouncementId = model.AnnouncementId;
                sysAnnouncement.Popups = model.Popups;
                sysAnnouncement.Subject = model.Subject;
                sysAnnouncement.Content = model.Content;
                sysAnnouncement.Sdate = model.Sdate;
                sysAnnouncement.Edate = model.Edate;
                _context.SaveChanges();
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <returns></returns>
        public bool Delete(int id)
        {

            //实例化一个UserInfo对象，并指定Id的值
            SysAnnouncement sysAnnouncement = new SysAnnouncement()
            {
                AnnouncementId = id
            };
            //将UserInfo附加到上下文对象中，并获得EF容器的管理对象
            var result = _context.Entry<SysAnnouncement>(sysAnnouncement);
            //设置该对象的状态为删除
            result.State = EntityState.Deleted;
            //保存修改
            _context.SaveChanges();

            return true;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public bool UpdateStatus(int id, sbyte status)
        {
            //官方推荐的修改方式（先查询，再修改）
            var model = _context.SysAnnouncement.Where(p => p.AnnouncementId.Equals(id)).FirstOrDefault();
            if (model != null)
            {
                model.Popups = status;
                int row = _context.SaveChanges();
                return true;
            }
            else
            {
                throw new Exception("当前记录不存在！");
            }
        }

        /// <summary>
        /// 更新弹窗
        /// </summary>
        /// <returns></returns>
        public bool UpdatePopups(int? announcementId)
        {
            var sql = $"update SysAnnouncement set Popups={(sbyte)Popups.不弹窗}";
            if (announcementId.HasValue) {
                sql += $" where announcementId!={announcementId}";
            }

            _context.Database.ExecuteSqlCommand(sql);
            return true;
        }

        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <returns></returns>
        public JResult<List<SysAnnouncementResponse>> GetList(SysAnnouncementQuery query)
        {
            var response = new JResult<List<SysAnnouncementResponse>>() {
                Success = true
            };

            if (query.UserPermission.Contains("SysConfig0007")) {
                response.StatusCode = "SysConfig0007";
            }

            var list = _context.SysAnnouncement.OrderByDescending(p=>p.CreateDate).ToList();

            var sysAnnouncements = new List<SysAnnouncementResponse>();

            foreach (var item in list)
            {
                var nowTime = DateTime.Now;

                var sysAnnouncementResponse = new SysAnnouncementResponse() {
                    AnnouncementId = item.AnnouncementId,
                    Popups = item.Popups,
                    Subject = item.Subject,
                    Content = item.Content,
                    Sdate = item.Sdate.ToString("yyyy-MM-dd HH:mm:ss"),
                    Edate = item.Edate.ToString("yyyy-MM-dd HH:mm:ss"),
                    Valid = (item.Sdate <= nowTime && item.Edate >= nowTime)?(sbyte)1:(sbyte)0,
                    CreateId = item.CreateId,
                    CreateDate = item.CreateDate,
                };
                if (query.UserPermission.Contains("SysConfig0007"))
                {
                    sysAnnouncementResponse.EditPermission = "SysConfig0007";
                }
                if (query.UserPermission.Contains("SysConfig0008"))
                {
                    sysAnnouncementResponse.DeletePermission = "SysConfig0008";
                }
                sysAnnouncements.Add(sysAnnouncementResponse);
            }
            if (sysAnnouncements != null && sysAnnouncements.Any()) {
                response.Data = sysAnnouncements;
            }
            return response;
        }
    }
}
